package com.markerhub.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.markerhub.common.dto.LoginDto;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.User;
import com.markerhub.service.UserService;
import com.markerhub.shiro.JwtToken;
import com.markerhub.util.JwtUtils;

import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.security.Security;

/**
 * @author cxz
 * 登录控制
 * @version 1.0
 */
@RestController
public class AccountController {

    @Autowired
    private UserService userService;
    @Autowired
    JwtUtils jwtUtils;


    @PostMapping("/login")
    public Result  login(@Validated  @RequestBody LoginDto loginDto , HttpServletResponse httpServletResponse) {
        System.out.println("dfgsasgadfgdas");
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        Assert.notNull(user, "用户不存在");
        if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
            return Result.fail("密码不正确");
        }
        System.out.println("dfgsasgadfgdas");
        String jwt = jwtUtils.generateToken(user.getId());
        httpServletResponse.setHeader("Authorization", jwt);
        httpServletResponse.setHeader("Access-Control-Expose-Headers", "Authorization");
        // 用户可以另一个接口
        System.out.println("dfgsasgadfgdas");
        return Result.success(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .map()

        );


    }

    @RequiresAuthentication
    @GetMapping("/logout")
    public Result  logout(){

        SecurityUtils.getSubject().logout();
        return Result.success(null);
    }
}
